package com.proyecto.miniplan.server;

import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.proyecto.miniplan.client.GreetingService;
import com.proyecto.miniplan.server.gdata.GdataManager;
import com.proyecto.miniplan.server.velocity.VelocityEngineManager;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	public int contador = 0;
	
	public String greetServer(String input) {
		//generate the document
		VelocityEngineManager.init();
		VelocityContext context = new VelocityContext();
		context.put("name", input);
		Template t = VelocityEngineManager.getTemplate("mytemplate.vm");
		StringWriter writer = new StringWriter();
		try {
			t.merge(context, writer);
		} catch (Exception e) {
			e.printStackTrace();
			return "troubles merging your template " + e.getMessage();
		} 
		
		//create the doc on google docs
		String newDocId = "<error>";
		try {
			String title = "test doc for inpu";
			String content = writer.toString();
			newDocId = GdataManager.manager().createNewDocument(title,content).getResourceId();
			
			//GdataManager.manager().getDocument(newDocId).setContent();
			
		} catch (Exception e) {


			//e.printStackTrace();
			return "error interfacing with Google Docs, see your logs";
		}

		
		//return the id
		return "I've just created a document with resource id " +
				"<a target=\"_blank\" href=\"./pdf?id=" + newDocId +"\">" + newDocId + "</a>";
	}
	

	

	
}
